<?php

class SectionsAction extends fvAction {
    
    function __construct () {
        parent::__construct(fvSite::$Layoult);
    }

    function executeIndex() {
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_NO_LAYOULT;
        else return self::$FV_OK;
    }
    
    function executeEdit() {
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else return self::$FV_OK;
    }
    
    function executeSave() {
        $request = fvRequest::getInstance();
        
        if (!$Section = SectionsManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
            $Section = new Sections();
        }
        $mn = $request->getRequestParameter('mn');
        if ($Section->isNew()) {
            $mn['menu_order'] = SectionsManager::getInstance()->getCount('parent_id = ?', array($mn['parent_id']));
        }
        $Section->updateFromRequest($mn);
        if ($Section->save()) {
        	$message = "Данные успешно сохранены";
        	if ($mn["discount"]){
        		$params_tmp[] = $Section->getPk();
                $result[] = $Section->getPk();
               	$stop = 1;
                do{
                	$SectionsUpdate = SectionsManager::getInstance()->getAll("parent_id in (".implode(',', $params_tmp).")");
                	$params_tmp = array ();
                	if (count($SectionsUpdate)){
	                	foreach ($SectionsUpdate as $SectionUpdate){
	                		$params_tmp[] = $SectionUpdate->getPk();
	                		$result = array_unique(array_merge($params_tmp, $result));    		
	                	}
                	}
	                else{
	                	$stop = 0;
	                } 
                } while ($stop!=0);
                $params = implode(',', $result);
                $SectionsToUpdate = SectionsManager::getInstance()->getAll("id in (".$params.")");
                foreach ($SectionsToUpdate as $stu){
                	$stu->discount = $mn["discount"];
                	$stu->save();
                }
        		$ProductsToUpdate = ProductsManager::getInstance()->getAll("category_id in (".$params.")");
                foreach ($ProductsToUpdate as $ptu){
                	$ptu->discount = $mn["discount"];
                	$ptu->save();
                }
                $message .= ". Обновлено ".count($SectionsToUpdate)." категорий и ".count($ProductsToUpdate)." товаров";
        	}
        if ($mn["filters"]){
        		$params_tmp[] = $Section->getPk();
                $result[] = $Section->getPk();
               	$stop = 1;
                do{
                	$SectionsUpdate = SectionsManager::getInstance()->getAll("parent_id in (".implode(',', $params_tmp).")");
                	$params_tmp = array ();
                	if (count($SectionsUpdate)){
	                	foreach ($SectionsUpdate as $SectionUpdate){
	                		$params_tmp[] = $SectionUpdate->getPk();
	                		$result = array_unique(array_merge($params_tmp, $result));    		
	                	}
                	}
	                else{
	                	$stop = 0;
	                } 
                } while ($stop!=0);
                $params = implode(',', $result);
                $SectionsToUpdate = SectionsManager::getInstance()->getAll("id in (".$params.")");
                foreach ($SectionsToUpdate as $stu){
                	$stu->filters = stripslashes($mn["filters"]);
                	$stu->save();
                }
        		$message .= ". Обновлено ".count($SectionsToUpdate)." категорий";
        	}
            fvResponce::getInstance()->setHeader('Id', $Section->getPk());
            $this->setFlash($message, self::$FLASH_SUCCESS);
            fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/?_rand=". rand());        
        } else { 
            fvResponce::getInstance()->setHeader('X-JSON', json_encode($Section->getValidationResult()));
            $this->setFlash("Ошибка при сохранении данных проверте правильность введенных данных", self::$FLASH_ERROR);
        }
        
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else return self::$FV_OK;
    }

    private function getObjectById($array, $id) {
        foreach ($array as $key => $object) {
            if ($object->getPk() == $id) return $key;
        }
        return -1;
    }
    
    function executeReorder() {
        $Sections = SectionsManager::getInstance()->getAll();
        $sortableOrder = fvRequest::getInstance()->getRequestParameter("sortables");
        foreach ($sortableOrder as $menuOrder => $menuContent) {
            $menuId = $menuContent['id'];
            if (($menuKey = $this->getObjectById($Sections, $menuId)) != -1) {
                $Sections[$menuKey]->parent_id = 0;
                $Sections[$menuKey]->menu_order = $menuOrder;
            }
            if (count($menuContent) > 1) {
                $parentId = $menuContent['id'];
                unset($menuContent['id']);
                foreach ($menuContent as $menuOrder => $menuSubContent) {
                    $menuId = $menuSubContent['id'];
                    if (($menuKey = $this->getObjectById($Sections, $menuId)) != -1) {
                        $Sections[$menuKey]->parent_id = $parentId;
                        $Sections[$menuKey]->menu_order = $menuOrder;
                    }
                }
            }
        }
        foreach ($Sections as $menu) {
            $menu->save(false);
        }
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else return self::$FV_OK;
    }

    function executeDelete() {
        $request = fvRequest::getInstance();
        if (!$Section = SectionsManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
            $this->setFlash("Ошибка при удалении.", self::$FLASH_ERROR);
        } else {
            $Section->delete();
            $this->setFlash("Данные успешно удалены", self::$FLASH_SUCCESS);
        }
        
        fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/");
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_NO_LAYOULT;
        else return self::$FV_OK;
    }
    
}

?>
